package term

import (
	"bufio"
	"io"
	"os"
	"strconv"
	"strings"

	"golang.org/x/sys/unix"
)

type State struct {
	termios unix.Termios
}

//
const (
	ioctlReadTermios  = 0x5401 // syscall.TCGETS
	ioctlWriteTermios = 0x5402 // syscall.TCSETS
)

// IsTerminal returns whether the given file descriptor is a terminal.
func IsTerminal(fd int) bool {
	_, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
	return err == nil
}

// MakeRaw puts the terminal connected to the given file descriptor into raw
// mode and returns the previous state of the terminal so that it can be
// restored.
func MakeRaw(fd int) (*State, error) {
	termios, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
	if err != nil {
		return nil, err
	}

	oldState := State{termios: *termios}

	// This attempts to replicate the behaviour documented for cfmakeraw in
	// the termios(3) manpage.
	termios.Iflag &^= unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP | unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON
	termios.Oflag &^= unix.OPOST
	termios.Lflag &^= unix.ECHO | unix.ECHONL | unix.ICANON | unix.ISIG | unix.IEXTEN
	termios.Cflag &^= unix.CSIZE | unix.PARENB
	termios.Cflag |= unix.CS8
	termios.Cc[unix.VMIN] = 1
	termios.Cc[unix.VTIME] = 0
	if err := unix.IoctlSetTermios(fd, ioctlWriteTermios, termios); err != nil {
		return nil, err
	}

	return &oldState, nil
}

// GetState returns the current state of a terminal which may be useful to
// restore the terminal after a signal.
//func GetState(fd int) (*State, error) {
//return getState(fd)
//}

// Restore restores the terminal connected to the given file descriptor to a
// previous state.
func Restore(fd int, oldState *State) error {
	return unix.IoctlSetTermios(fd, ioctlWriteTermios, &oldState.termios)
}

func GetSize(fd int) (int, int, error) {
	ws, err := unix.IoctlGetWinsize(fd, unix.TIOCGWINSZ)
	if err != nil {
		return -1, -1, err
	}
	return int(ws.Col), int(ws.Row), nil
}

const (
	Esc = "\u001B["
	Osc = "\u001B]"
	Bel = "\u0007"
)

type Term struct {
	trs  *bufio.Reader
	tws  io.Writer
	w, h int
	x, y int
}

func NewTerm(w, h int) *Term {
	t := &Term{bufio.NewReader(os.Stdin), os.Stdout, w, h, 0, 0}
	t.y = 10

	/**/
	tt := Esc + "2J"
	t.tws.Write([]byte(tt))
	return t
}

func (t *Term) SetCusorPos(x, y int) {
	tt := Esc + strconv.Itoa(y+1) + ";" + strconv.Itoa(x+1) + "H"
	/**/
	t.tws.Write([]byte(tt))
	return
}

func (t *Term) GetKeys() (rune, error) {

	/**/
	rne, _, err := t.trs.ReadRune()
	return rne, err
}

func (t *Term) ScrollUp(n int) {
	tt := Esc + strconv.Itoa(n) + "S"
	t.tws.Write([]byte(tt))
	return
}

func (t *Term) EraseLine() {
	tt := Esc + "2K"
	t.tws.Write([]byte(tt))
	return
}

func (t *Term) WriteString(ss string) {

	/**/
	lins := strings.Split(ss, "\n")
	for _, aa := range lins {

		/**/
		if t.y > (t.h - 4) {

			/* scroll up */
			// tt := Esc + "S"
			// t.tws.Write([]byte(tt))

			yy := Esc + strconv.Itoa(t.y+1) + ";" + strconv.Itoa(t.x+1) + "H"
			t.tws.Write([]byte(yy))

			t.tws.Write([]byte(Esc + "34;1m"))
			t.tws.Write([]byte(aa))

		} else {

			tt := Esc + strconv.Itoa(t.y+1) + ";" + strconv.Itoa(t.x+1) + "H"
			t.tws.Write([]byte(tt))

			/* color */
			t.tws.Write([]byte(Esc + "34;1m"))
			t.tws.Write([]byte(aa))
		}

	}

	return
}

func (t *Term) GotoCliPos() {

	tt := Esc + strconv.Itoa(t.h+1) + ";" + strconv.Itoa(1) + "H"
	t.tws.Write([]byte(tt))

	/* color reset */
	t.tws.Write([]byte(Esc + "0m"))
	return
}

func (t *Term) ScrollLines(n int) {

	var tt string

	/**/
	tt = Esc + strconv.Itoa(t.h) + ";" + strconv.Itoa(1) + "H"
	t.tws.Write([]byte(tt))
	tt = Esc + "2K"
	t.tws.Write([]byte(tt))

	/**/
	tt = Esc + strconv.Itoa(t.h+1) + ";" + strconv.Itoa(1) + "H"
	t.tws.Write([]byte(tt))
	tt = Esc + "2K"
	t.tws.Write([]byte(tt))

	/**/
	tt = strings.Repeat("\r\n", n)
	t.tws.Write([]byte(tt))
	return
}
